package com.yzc.android.common.utils;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by 陈阳(chenyang@edaijia-staff.cn>)
 * Date: 7/7/14 4:27 PM.
 */
public final class LoggerSave {

    final static SimpleDateFormat MD_HMS = new SimpleDateFormat("MM-dd HH:mm:ss");

    public static final Handler WRITE_HANDLER = new Handler(new HandlerThread("write_log") {{
        start();
    }}.getLooper()) {
        FileWriter mWriter;

        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            Bundle bundle = msg.getData();
            String filePath = bundle.getString("filePath");
            String fileName = bundle.getString("fileName");
            String log = bundle.getString("log");
            if (filePath == null) {
                return;
            }
            File folder = new File(filePath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            File file = new File(folder, fileName);
            try {
                mWriter = new FileWriter(file, true);
            } catch (IOException e) {
                e.printStackTrace();
                mWriter = null;
            }
            if (mWriter == null) {
                return;
            }
            try {
                mWriter.write(MD_HMS.format(new Date()) + " : " + log + '\n');
                mWriter.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    mWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * 默认文件夹
     */
    private static final String BASE_FOLDER = Environment.getExternalStorageDirectory().getAbsolutePath() + "/edaijia";

    /**
     * Log文件保存地址
     */
    private static final String LOG_NAME = "log.txt";

    private static final String LOG_STATISTICS_NAME = "statistics.txt";

    private static final String LOG_DETAIL_FOLDER = BASE_FOLDER + "/LogDetail";

    private static void asyncWriteLog(String filePath, String fileName, String log) {
        Message msg = WRITE_HANDLER.obtainMessage();
        Bundle bundle = new Bundle();
        bundle.putString("filePath", filePath);
        bundle.putString("fileName", fileName);
        bundle.putString("log", log);
        msg.setData(bundle);
        WRITE_HANDLER.sendMessage(msg);
    }

    /**
     * 分类打印日志，根据文件名分类日志。存放于logDetail目录下
     */
    public static void vDetail(String fileName, String msg) {
        String v = Thread.currentThread().getId() + msg;
        if (!TextUtils.isEmpty(fileName)) {
            String filePath = LOG_DETAIL_FOLDER;
            fileName = fileName + ".txt";
            asyncWriteLog(filePath, fileName, v);
        }
    }

    /**
     * 打印出所有信息的日志，集存于一个文件
     */
    public static void v(String msg) {
        String v = Thread.currentThread().getId() + msg;
        asyncWriteLog(BASE_FOLDER, LOG_NAME, v);
    }

    /**
     * 用于统计api调用次数的日志
     */
    public static void vStatistics(String msg) {
        asyncWriteLog(BASE_FOLDER, LOG_STATISTICS_NAME, msg);
    }

    public static void exception(Throwable throwable) {
        v(Log.getStackTraceString(throwable));
    }
}
